import { $fetch } from 'ofetch';
import { ElMessage } from "element-plus";
import { useUserStore } from "../store/useUser";
import { useRouter } from 'vue-router';

interface RequestOptions {
    customBaseURL?: string;
    [key: string]: any;
}

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

const authApi = [
    '/msb/concernRecord/buyerConcern',
    '/msb/shopCar/addShopCar',
]

// 请求拦截器
function handleRequest(options: RequestOptions) {
    // 在 SSR 环境下安全地获取 token
    const token = process.client ? localStorage.getItem('token') : null;
    
    console.log('handleRequest - token:', token);

    options.headers = {
        'Content-Type': 'application/json',
        'clientid': 'e5cd7e4891bf95d1d19206ce24a7b32e',
        'connection': 'keep-alive',
        'istoken': 'true',
        ...(token && { 'Authorization': `Bearer ${token}` }),
        ...options.headers,
    };
    
    console.log('handleRequest - headers:', options.headers);
}

// 响应拦截器
function handleResponse(response: any) {
    if (response.error) {
        throw new Error(response.error.message || '响应错误');
    }
    if (response.code === 401) {
        const router = useRouter();
        const userStore = useUserStore();
        
        // 防止重复处理401
        if (userStore.isLoggingOut) {
            return response;
        }
        
        ElMessage.error(response.msg || '登录已过期，请重新登录！');
        
        // 直接清除本地存储，不调用logout API避免循环
        try {
            if (process.client) {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
            }
            userStore.userInfo = {};
            userStore.token = '';
            router.push('/login');
        } catch (error) {
            console.error('清除登录信息失败:', error);
        }
    }
    if (response.code !== 200) {
        ElMessage.error(response.msg);
        throw new Error(response);
    }
    return response;
}

/**
 * 创建请求方法
 * @param method
 */
function createDollarFetchRequest(method: HttpMethod) {
    return async function (
        url: string,
        data?: any,
        options: RequestOptions = {}
    ) {
        try {
            const userStore = useUserStore();
            const findAuthApi = authApi.find(item => url.indexOf(item) !== -1)
            console.log('findAuthApi', findAuthApi)
            if (findAuthApi && !userStore.isLogin) {
                const router = useRouter();
                router.push('/login')
                return
            }
            handleRequest(options);
            const response = await $fetch(url, {
                method,
                body: data,
                ...options,
            });
            return handleResponse(response);
        } catch (error) {
            console.error('请求错误:', error);
            throw error;
        }
    };
}


// 提供 $fetch & HTTP 方法 - 统一管理请求 - 再到组件中使用
export const useDollarGet = createDollarFetchRequest('GET');
export const useDollarPost = createDollarFetchRequest('POST');
export const useDollarPut = createDollarFetchRequest('PUT');
export const useDollarDelete = createDollarFetchRequest('DELETE');